import '../models/heritage_activity.dart';

class HeritageActivityService {
  static final HeritageActivityService _instance = HeritageActivityService._internal();
  factory HeritageActivityService() => _instance;
  HeritageActivityService._internal();

  final List<HeritageActivity> _activities = [];
  final Map<String, List<String>> _userRegistrations = {};
  final Map<String, List<String>> _userParticipations = {};

  /// 初始化模拟数据
  void initializeMockData() {
    _activities.clear();
    _activities.addAll([
      HeritageActivity(
        id: '1',
        title: '传统书法体验课',
        description: '学习中国传统书法艺术，体验毛笔字的魅力',
        imageUrl: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=Chinese%20calligraphy%20class%20traditional%20brush%20writing&image_size=landscape_4_3',
        category: 'workshop',
        startDate: DateTime.now().add(const Duration(days: 3)),
        endDate: DateTime.now().add(const Duration(days: 3, hours: 2)),
        location: '文化中心书法室',
        maxParticipants: 20,
        currentParticipants: 15,
        price: 80.0,
        organizer: '中华书法协会',
        contactInfo: '010-12345678',
        requirements: '无需基础，自备练习本',
        highlights: ['专业老师指导', '提供文房四宝', '作品可带走'],
        status: ActivityStatus.upcoming,
        tags: ['书法', '传统文化', '艺术'],
        rating: 4.8,
        reviewCount: 25,
        isFeatured: true,
        isRecommended: true,
        createdAt: DateTime.now().subtract(const Duration(days: 7)),
        updatedAt: DateTime.now().subtract(const Duration(days: 1)),
      ),
      HeritageActivity(
        id: '2',
        title: '非遗剪纸艺术展',
        description: '展示中国传统剪纸艺术的精美作品，了解剪纸文化历史',
        imageUrl: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=Chinese%20paper%20cutting%20art%20exhibition%20traditional%20red%20patterns&image_size=landscape_4_3',
        category: 'exhibition',
        startDate: DateTime.now().add(const Duration(days: 1)),
        endDate: DateTime.now().add(const Duration(days: 30)),
        location: '民俗博物馆一楼展厅',
        maxParticipants: 200,
        currentParticipants: 45,
        price: 0.0,
        organizer: '民俗博物馆',
        contactInfo: '010-87654321',
        requirements: '免费参观，需预约',
        highlights: ['百年传承作品', '互动体验区', '专家讲解'],
        status: ActivityStatus.upcoming,
        tags: ['剪纸', '非遗', '展览'],
        rating: 4.6,
        reviewCount: 18,
        isFeatured: false,
        isRecommended: true,
        createdAt: DateTime.now().subtract(const Duration(days: 10)),
        updatedAt: DateTime.now().subtract(const Duration(days: 2)),
      ),
      HeritageActivity(
        id: '3',
        title: '古琴雅集音乐会',
        description: '聆听古琴大师演奏，感受中国古典音乐的韵味',
        imageUrl: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=Chinese%20guqin%20concert%20traditional%20music%20performance&image_size=landscape_4_3',
        category: 'performance',
        startDate: DateTime.now().add(const Duration(days: 7)),
        endDate: DateTime.now().add(const Duration(days: 7, hours: 2)),
        location: '音乐厅',
        maxParticipants: 100,
        currentParticipants: 80,
        price: 120.0,
        organizer: '古琴学会',
        contactInfo: '010-11223344',
        requirements: '正装出席，禁止录音录像',
        highlights: ['国家级演奏家', '经典曲目', '茶歇交流'],
        status: ActivityStatus.upcoming,
        tags: ['古琴', '音乐', '雅集'],
        rating: 4.9,
        reviewCount: 32,
        isFeatured: true,
        isRecommended: false,
        createdAt: DateTime.now().subtract(const Duration(days: 14)),
        updatedAt: DateTime.now().subtract(const Duration(days: 3)),
      ),
      HeritageActivity(
        id: '4',
        title: '传统茶艺文化讲座',
        description: '了解中国茶文化历史，学习基本茶艺技巧',
        imageUrl: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=Chinese%20tea%20ceremony%20culture%20lecture%20traditional%20teapot&image_size=landscape_4_3',
        category: 'lecture',
        startDate: DateTime.now().subtract(const Duration(days: 2)),
        endDate: DateTime.now().subtract(const Duration(days: 2, hours: -3)),
        location: '茶文化研究中心',
        maxParticipants: 50,
        currentParticipants: 50,
        price: 60.0,
        organizer: '茶文化研究会',
        contactInfo: '010-55667788',
        requirements: '提前报名，自备笔记本',
        highlights: ['专家授课', '品茶体验', '茶具展示'],
        status: ActivityStatus.completed,
        tags: ['茶艺', '文化', '讲座'],
        rating: 4.7,
        reviewCount: 28,
        isFeatured: false,
        isRecommended: false,
        createdAt: DateTime.now().subtract(const Duration(days: 20)),
        updatedAt: DateTime.now().subtract(const Duration(days: 2)),
      ),
    ]);
  }

  /// 获取所有活动
  Future<List<HeritageActivity>> getAllActivities() async {
    await Future.delayed(const Duration(milliseconds: 500));
    if (_activities.isEmpty) {
      initializeMockData();
    }
    return List.from(_activities);
  }

  /// 根据分类获取活动
  Future<List<HeritageActivity>> getActivitiesByCategory(ActivityCategory category) async {
    await Future.delayed(const Duration(milliseconds: 300));
    if (_activities.isEmpty) {
      initializeMockData();
    }
    return _activities.where((activity) => activity.category == category).toList();
  }

  /// 根据状态获取活动
  Future<List<HeritageActivity>> getActivitiesByStatus(ActivityStatus status) async {
    await Future.delayed(const Duration(milliseconds: 300));
    if (_activities.isEmpty) {
      initializeMockData();
    }
    return _activities.where((activity) => activity.status == status).toList();
  }

  /// 获取推荐活动
  Future<List<HeritageActivity>> getRecommendedActivities() async {
    await Future.delayed(const Duration(milliseconds: 400));
    if (_activities.isEmpty) {
      initializeMockData();
    }
    // 返回即将开始的活动，按参与人数排序
    final upcomingActivities = _activities
        .where((activity) => activity.status == ActivityStatus.upcoming)
        .toList();
    upcomingActivities.sort((a, b) => b.currentParticipants.compareTo(a.currentParticipants));
    return upcomingActivities.take(5).toList();
  }

  /// 获取热门活动
  Future<List<HeritageActivity>> getPopularActivities() async {
    await Future.delayed(const Duration(milliseconds: 400));
    if (_activities.isEmpty) {
      initializeMockData();
    }
    // 按参与人数排序
    final sortedActivities = List<HeritageActivity>.from(_activities);
    sortedActivities.sort((a, b) => b.currentParticipants.compareTo(a.currentParticipants));
    return sortedActivities.take(10).toList();
  }

  /// 根据ID获取活动详情
  Future<HeritageActivity?> getActivityById(String id) async {
    await Future.delayed(const Duration(milliseconds: 200));
    if (_activities.isEmpty) {
      initializeMockData();
    }
    try {
      return _activities.firstWhere((activity) => activity.id == id);
    } catch (e) {
      return null;
    }
  }

  /// 报名参加活动
  Future<bool> registerForActivity(String activityId, String userId) async {
    await Future.delayed(const Duration(milliseconds: 500));
    
    final activity = await getActivityById(activityId);
    if (activity == null) {
      throw Exception('活动不存在');
    }
    
    if (activity.currentParticipants >= activity.maxParticipants) {
      throw Exception('活动已满员');
    }
    
    if (activity.status != ActivityStatus.upcoming) {
      throw Exception('活动不在报名期间');
    }
    
    // 检查是否已经报名
    if (_userRegistrations[userId]?.contains(activityId) == true) {
      throw Exception('您已经报名了此活动');
    }
    
    // 添加报名记录
    _userRegistrations.putIfAbsent(userId, () => []).add(activityId);
    
    // 增加参与人数
    final index = _activities.indexWhere((a) => a.id == activityId);
    if (index != -1) {
      _activities[index] = _activities[index].copyWith(
        currentParticipants: _activities[index].currentParticipants + 1,
      );
    }
    
    return true;
  }

  /// 取消报名
  Future<bool> cancelRegistration(String activityId, String userId) async {
    await Future.delayed(const Duration(milliseconds: 300));
    
    if (_userRegistrations[userId]?.contains(activityId) != true) {
      throw Exception('您未报名此活动');
    }
    
    // 移除报名记录
    _userRegistrations[userId]?.remove(activityId);
    
    // 减少参与人数
    final index = _activities.indexWhere((a) => a.id == activityId);
    if (index != -1) {
      _activities[index] = _activities[index].copyWith(
        currentParticipants: _activities[index].currentParticipants - 1,
      );
    }
    
    return true;
  }

  /// 获取用户报名的活动
  Future<List<HeritageActivity>> getUserRegisteredActivities(String userId) async {
    await Future.delayed(const Duration(milliseconds: 300));
    
    final registeredIds = _userRegistrations[userId] ?? [];
    final registeredActivities = <HeritageActivity>[];
    
    for (final id in registeredIds) {
      final activity = await getActivityById(id);
      if (activity != null) {
        registeredActivities.add(activity);
      }
    }
    
    return registeredActivities;
  }

  /// 获取用户参与的活动
  Future<List<HeritageActivity>> getUserParticipatedActivities(String userId) async {
    await Future.delayed(const Duration(milliseconds: 300));
    
    final participatedIds = _userParticipations[userId] ?? [];
    final participatedActivities = <HeritageActivity>[];
    
    for (final id in participatedIds) {
      final activity = await getActivityById(id);
      if (activity != null) {
        participatedActivities.add(activity);
      }
    }
    
    return participatedActivities;
  }

  /// 检查用户是否已报名某活动
  Future<bool> isUserRegistered(String activityId, String userId) async {
    await Future.delayed(const Duration(milliseconds: 100));
    return _userRegistrations[userId]?.contains(activityId) == true;
  }

  /// 搜索活动
  Future<List<HeritageActivity>> searchActivities(String query) async {
    await Future.delayed(const Duration(milliseconds: 400));
    if (_activities.isEmpty) {
      initializeMockData();
    }
    
    if (query.isEmpty) {
      return List.from(_activities);
    }
    
    final lowercaseQuery = query.toLowerCase();
    return _activities.where((activity) {
      return activity.title.toLowerCase().contains(lowercaseQuery) ||
          activity.description.toLowerCase().contains(lowercaseQuery) ||
          activity.tags.any((tag) => tag.toLowerCase().contains(lowercaseQuery));
    }).toList();
  }

  /// 清除所有数据（用于测试）
  void clearAllData() {
    _activities.clear();
    _userRegistrations.clear();
    _userParticipations.clear();
  }
}